#ifndef _DatasetIO_dataset_io_panoseq_H_
#define _DatasetIO_dataset_io_panoseq_H_

#include "dataset_io.h"

namespace DatasetIO {

class PanoSeqDataset : public Dataset {
    std::string path;

    std::vector<double> image_timestamps;
    std::string image_path;

    std::shared_ptr<cv::VideoCapture> pano_vicap_ptr;
    size_t cur_image_id;

    std::vector<AccelData::Ptr> accel_data;
    std::vector<GyroData::Ptr> gyro_data;

public:
    PanoSeqDataset() : Dataset() { type = DatasetType::kPanoSeq; }
    ~PanoSeqDataset(){};

    std::vector<double> &get_image_timestamps() { return image_timestamps; }

    const std::vector<AccelData::Ptr> &get_accel_data() const {
        return accel_data;
    }
    const std::vector<GyroData::Ptr> &get_gyro_data() const {
        return gyro_data;
    }

    MonoImageData::Ptr get_next_mono_image_data() {
        MonoImageData::Ptr res;
        cv::Mat image;

        if (pano_vicap_ptr->read(image)) {
            double t_s = image_timestamps[cur_image_id++];
            res = std::make_shared<MonoImageData>();
            res->timestamp = t_s;
            res->data = image.clone();
        }

        return res;
    }

    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    friend class PanoSeqIO;
};

class PanoSeqIO : public DatasetIoInterface {
public:
    PanoSeqIO() {}

    void read(const std::string &path) {
        if (!fs::exists(path))
            LOG(WARNING) << "No dataset found in " << path;

        data.reset(new PanoSeqDataset);

        data->path = path;
        data->pano_vicap_ptr = std::make_shared<cv::VideoCapture>(
            path + "/video.mp4", cv::CAP_FFMPEG);
        data->cur_image_id = 0;

        read_image_timestamps(path + "/times.txt");
    }

    void reset() { data.reset(); }

    Dataset::Ptr get_data() { return data; }

private:
    void read_image_timestamps(const std::string &path) {
        std::ifstream f(path);
        std::string line;
        while (std::getline(f, line)) {
            if (line[0] == '#' || line == "")
                continue;
            std::stringstream ss(line);

            double t_s;
            ss >> t_s;
            data->image_timestamps.emplace_back(t_s * 1e-9);
        }
    }

    std::shared_ptr<PanoSeqDataset> data;
};

}  // namespace DatasetIO

#endif